function varargout = TLLookupNDDirectDlg(action,varargin)

% TL_LOOKUPNDDIRECT_DLG manages the user interface for TargetLink Direct Look-Up Table block
%
% SYNTAX dlgInfo = TLLookupnddirectDlg('GetDlgInfo');
%   gets dialog info of TargetLink Direct Look-Up Table block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLLookupnddirectDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLLookupnddirectDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLLookupnddirectDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLLookupnddirectDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLLookupnddirectDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLLookupnddirectDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.21 $
% $Date: 2011/05/12 08:08:23MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Direct Look-Up Table (n-D)';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {
            'General';
            'Output';
            'Table';
            'Logging & Autoscaling';
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);
        
    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        excludedCtrls = {'saturate', 'inheritproperties'};
        switch pageName
            case 'General'
                [sheetDims, ctrlPos] = FcnCalcGeneralCtrlPositions(commonGeom);
                
            case 'Output'
                [sheetDims, ctrlPos] = tl_calc_ctrls_positions(commonGeom, excludedCtrls);
                
            case 'Table'
                [sheetDims, ctrlPos] = FcnCalcTableCtrlPositions(commonGeom);
                
            case 'Logging & Autoscaling'
                excludedCtrls = {};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);
                
            case 'Documentation'
                % no extra table controls
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims, ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos', commonGeom, sheetDims, ...
                    bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;
        
    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'General'
                dlgdata = FcnCreateGeneralCtrls(pageNum, dlgfig, dlgdata);
                
            case 'Output'
                dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
                dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);
                
            case 'Table'
                dlgdata = FcnCreateTableCtrls(pageNum, dlgfig, dlgdata);
                
            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;
        
    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'General'
                [dlgdata, bModified] = FcnManageGeneralCtrls(pageNum, dlgdata, pageAction);
                
            case 'Output'
                [dlgdata, bModified1] = ...
                    TLManageVariableCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'output');
                % output variable can be vectorized
                currentElement = dlgdata.extdata.output.currentElement;
                [dlgdata, bModified2] = ...
                    TLManageScalingCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'output', currentElement);
                
                bModified = bModified1 || bModified2;
                
            case 'Table'
                [dlgdata, bModified] = FcnManageTableCtrls(pageNum, dlgfig, ...
                    dlgdata, pageAction);
                
            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');
                
            case 'Documentation'
                [dlgdata,bModified] = TLManageDocCtrls('callback', ...
                    pageNum, dlgfig, dlgdata, pageAction);
                
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified ;
        
    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};
        
        pageName  = dlgdata.pageNames{pageNum};
        switch pageName
            case 'General'
                dlgdata = FcnUpdateGeneralCtrls(pageNum, dlgfig, dlgdata);
                
            case 'Output'
                dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'output');
                dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'output', []);
                
                TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
                TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);
                
            case 'Table'
                dlgdata = FcnUpdateTableCtrls(pageNum, dlgfig, dlgdata);
                
            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
                
            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;
        
    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;
        
    otherwise
        error(['Invalid action "' action '"']);
        
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        switch dlgdata.pageNames{dlgdata.CurrentPageNum}
            case 'Table'
                blockVar = 'table';
                tl_create_links_to_model('ShowDeclaration',dlgdata.model, blockVar);
            otherwise
                blockVar = 'output';
                tl_create_links_to_model('ShowComputation',dlgdata.model, blockVar);
        end

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnCalcGeneralCtrlPositions calculates positions for all controls on table page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcGeneralCtrlPositions(commonGeom)

% get sheet dimension of output tab
[sheetDims, outputCtrlPos, col, colDelta, rowDelta] = tl_calc_ctrls_positions(commonGeom, ...
    {'allscaling', 'scaling', 'type', 'class', 'var', 'element', 'width', 'address' 'name', 'unit', 'scalarExp', 'inheritproperties'});

strings_and_styles = {...
    'Table:',                                 'text';
    repmat('m',69),                          'edit';
    'Make table an input',                    'checkbox';
    ' Scale Table ',                          'pushbutton';
    'Number of table dimensions:',            'text';
    '2     ',                                 'popupmenu';
    'Inputs select this object from table:',  'text';
    repmat('m',1,7),                          'popupmenu'};

[tableLabelSize, ...
    tableEditSize, ...
    tabIsInputCheckboxSize, ...
    autoscaleButtonSize, ...
    tableDimsLabelSize, ...
    tableDimsPopupSize, ...
    outDimensionLabelSize, ...
    uniPopupSize] = ...
    ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

% correct length of table edit field
wholeLength = outputCtrlPos.tlcgoptGroupbox(3) - 2*commonGeom.frameSideEdgeBuffer;
cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;

tableGroupboxWidth = outputCtrlPos.addoptGroupbox(3);
tableGroupboxHeight = 6 * commonGeom.editHeight ...
    + 5 * rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;
ctrlPos.tableGroupbox = [cx, cy, tableGroupboxWidth, tableGroupboxHeight];

% positions for table controls
%---------------------------------------
% 6th row
cy = commonGeom.frameBottomEdgeBuffer;

% autoscale button
cx = col(1);
ctrlPos.autoscaleButton = [cx cy 2*autoscaleButtonSize(1) autoscaleButtonSize(2)];

% clip action label
cx = col(1);
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.clipActionLabel = [cx,cy,outDimensionLabelSize];

% clip action popup
cx = cx + outDimensionLabelSize(1) + colDelta / 3;
ctrlPos.clipActionPopup = [cx cy uniPopupSize];

%---------------------------------------
% 4th row
% output dimension label
cy = cy + commonGeom.editHeight + rowDelta;
cx = col(1);
ctrlPos.outDimensionLabel = [cx cy outDimensionLabelSize];

% output dimension popup
cx = cx + outDimensionLabelSize(1) + colDelta / 3;
ctrlPos.outDimensionPopup = [cx cy uniPopupSize];

%---------------------------------------
% 3rd row
% number of table dimensions label
cx = col(1);
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.tableDimsLabel = [cx cy tableDimsLabelSize];

% number of table dimensions popup
cx = cx ...
    + outDimensionLabelSize(1) ...
    + colDelta / 3 ...
    + uniPopupSize(1) ...
    - tableDimsPopupSize(1);
ctrlPos.tableDimsPopup = [cx cy tableDimsPopupSize];

% table is input checkbox
cx = col(1);
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.tabIsInputCheckbox = [cx cy tabIsInputCheckboxSize];

% table label
cy = cy + commonGeom.editHeight + rowDelta;
cx = col(1);
ctrlPos.tableLabel = [cx cy tableLabelSize];

% table Edit
cx = col(2);
controlWidth = wholeLength - cx + ctrlPos.tableLabel(1);
ctrlPos.tableEdit =  [cx cy controlWidth tableEditSize(2)];

% increase sheet dimensions
sheetDims(2) = commonGeom.sheetTopEdgeBuffer ...
    + ctrlPos.tableGroupbox(4) ...
    + commonGeom.sheetBottomEdgeBuffer;


%-----------------------------------------------------------------------------------------
% FcnCreateGeneralCtrls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateGeneralCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
pageName = dlgdata.pageNames{pageNum};
% create the tableGroupbox which will contain table options
Children.tableGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Look-up options'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.tableGroupbox);

% table controls
Children.tableLabel = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'Style',              'text', ...
    'String',             'Table:', ...
    'Position',           ctrlPos.tableLabel);

Children.tableEdit = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.tableEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''tableEdit'')',pageName));

% number of table dimensions
Children.tableDimsLabel = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'Style',              'text', ...
    'String',             'Number of table dimensions:', ...
    'Position',           ctrlPos.tableDimsLabel);

Children.tableDimsPopup = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'Style',              'popupmenu', ...
    'BackgroundColor',    'w', ...
    'String',             {'1','2'}, ...
    'Position',           ctrlPos.tableDimsPopup, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''tableDimsPopup'')',pageName));

% make table an input checkbox
Children.tabIsInputCheckbox = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Make table an input', ...
    'Position',           ctrlPos.tabIsInputCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''tabIsInputCheckbox'')',pageName));

% output dimension controls
Children.outDimensionLabel = uicontrol( ...
    'Parent',            Children.tableGroupbox, ...
    'Style',             'text', ...
    'String',            'Inputs select this object from table:', ...
    'Position',          ctrlPos.outDimensionLabel);

Children.outDimensionPopup = uicontrol( ...
    'Parent',            Children.tableGroupbox, ...
    'Style',             'popupmenu', ...
    'BackgroundColor',   'w', ...
    'String',            {'Element','Column'}, ...
    'Position',          ctrlPos.outDimensionPopup, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''outDimensionPopup'')',pageName));

% clip action control
Children.clipActionLabel = uicontrol( ...
    'Parent',            Children.tableGroupbox, ...
    'Style',             'text', ...
    'String',            'Action for out-of-range input:', ...
    'Position',          ctrlPos.clipActionLabel);

Children.clipActionPopup = uicontrol( ...
    'Parent',            Children.tableGroupbox, ...
    'Style',             'popupmenu', ...
    'BackgroundColor',   'w', ...
    'String',            {'None','Warning','Error'}, ...
    'Position',          ctrlPos.clipActionPopup, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''clipActionPopup'')',pageName));

% autoscale button
Children.autoscaleButton = uicontrol( ...
    'Parent',             Children.tableGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             'Scale Table', ...
    'Position',           ctrlPos.autoscaleButton, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''autoscaleButton'')',pageName));

dlgdata.pageData{pageNum}.children  = Children;

%-----------------------------------------------------------------------------------------
% FcnManageGeneralCtrls manage control actions of General page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageGeneralCtrls(pageNum, dlgdata, action)

Children = dlgdata.pageData{pageNum}.children;
data = dlgdata.data;

switch action
    case 'tableEdit'
        tStr = deblank(get(Children.tableEdit, 'String'));
        if ~isempty(tStr)
            if strcmp(tStr, 'ddv')
                if isempty(dlgdata.data.table.variable)
                    beep;
                else
                    data.table.value = ['ddv(''', data.table.variable, ''')'];
                    data.table.useddvariablevalue = true;
                end
            else
                data.table.value = tStr;
                % since value was changed without respect to a DD variable,
                % useddvariablevalue is assumed as 'off'
                data.table.useddvariablevalue = false;
            end
        else
            beep;
        end
        bModified = true;
        
    case 'tableDimsPopup'
        data.ndims = get(Children.tableDimsPopup, 'Value');
        if data.ndims == 1,
            % from a one-dimensional table only an element could be selected
            data.outdims = 1;
        else
            % TargetLink doesn't support matrix signals, so the table data
            % cannot come from an input
            data.tabisinput = 0;
        end
        bModified = true;
        
    case 'tabIsInputCheckbox'
        data.tabisinput = get(Children.tabIsInputCheckbox, 'Value');
        bModified = true;
        
    case 'outDimensionPopup'
        data.outdims = get(Children.outDimensionPopup, 'Value');
        bModified = true;
        
    case 'clipActionPopup'
        data.clipflag = get(Children.clipActionPopup, 'Value');
        bModified = true;
        
    case 'autoscaleButton'
        ds_error_none;
        [data, bModified, msgstruct] = tl_scale_parameters( ...
            dlgdata.model, data);
        ds_error_register(msgstruct);
        ds_msgdlg('Update', ...
            'Title', ['Scaling of Direct Look-up Block ' get_tlsubsystempath(dlgdata.model) ], ...
            'ShowErrors','yes', ...
            'ShowNotes','yes', ...
            'ShowWarnings','yes');    
end

if bModified
    dlgdata.data = data;
end


%-----------------------------------------------------------------------------------------
% FcnUpdateGeneralCtrls updates General page
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateGeneralCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;

% default status of table controls
tableEditCtrlStatus = struct('enable', 'on', 'string', '');
tableDimsPopupCtrlStatus = struct('enable', 'on', ...
    'string', {{'1', '2'}}, ...
    'value', 2);
tabIsInputCheckboxCtrlStatus = struct('enable', 'on', ...
    'value', 0);
outDimensionPopupCtrlStatus = struct('enable', 'on', ...
    'string', {{'Element', 'Column'}}, ...
    'value', 1);
clipActionPopupCtrlStatus = struct('enable', 'on', ...
    'string', {{'None', 'Warning', 'Error'}}, ...
    'value', 2);
autoscaleButtonCtrlStatus = struct('enable', 'on');

data = dlgdata.data;

% get minima and maxima of table data
bReqMono = false;
bMatAllowed = dlgdata.data.ndims > 1;
[t, tmin, tmax, bCompliant] = tl_eval_table(dlgdata.data.table, bReqMono, bMatAllowed);

tableEditCtrlStatus.iserror = ~bCompliant;

if data.tabisinput
    tableEditCtrlStatus.string = '';
    tableEditCtrlStatus.enable = 'off';
else
    tableEditCtrlStatus.string = data.table.value;
    tableEditCtrlStatus.enable = 'on';
end

tableDimsPopupCtrlStatus.value = data.ndims;
tabIsInputCheckboxCtrlStatus.enable = flag2str(data.ndims == 1);
tabIsInputCheckboxCtrlStatus.value = data.tabisinput;
if data.ndims > 1
    outDimensionPopupCtrlStatus.enable = 'on';
else
    % 'inactive' only, so the currently selected item is still displayed
    outDimensionPopupCtrlStatus.enable = 'inactive';
end
outDimensionPopupCtrlStatus.value = data.outdims;
clipActionPopupCtrlStatus.value = data.clipflag;

% activation of 'Scale Table' button
% special behaviour of table blocks: Scale button must be disabled if 'no
% autoscaling' is selected
bOutputInteger = ds_isa(['/Pool/Typedefs/' data.output.type], 'integertype');
bAutoscEnable = bOutputInteger ...
    && isempty(dsdd('GetConstraintsScalingRef', ['/Pool/Typedefs/' data.output.type])) ...
    && isempty(data.output.scaling);
bScaleButtonEnable  = dlgdata.bIsFullVs && bAutoscEnable && data.autoscaling.mode == 1;
autoscaleButtonCtrlStatus.enable = flag2str(bScaleButtonEnable);

% set control status
ctrlsList = {
    'autoscaleButton' ...
    'tableEdit' ...
    'tableDimsPopup' ...
    'tabIsInputCheckbox' ...
    'outDimensionPopup' ...
    'clipActionPopup'};

for ctrlsNo = 1:numel(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end
TLSetCtrlsStatus(dlgfig, Children, ctrlsList);


%-----------------------------------------------------------------------------------------
% FcnCalcTableCtrlPositions calculates positions for all controls on Table page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcTableCtrlPositions(commonGeom)

excludedCtrls = {'saturate', 'inheritproperties', 'width', 'element', 'scalarExp'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = { ...
    'Table:', 'text'
    'Use value of Data Dictionary variable', 'checkbox'};

[tableLabelSize, useDDValueCheckboxSize] = ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

% control positions of controls of table options group box
% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + commonGeom.checkboxHeight ...
    + rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%---------------------------------------
% 2nd row
cy = commonGeom.frameBottomEdgeBuffer;

% ddv checkbox
cx = col(2);
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

%---------------------------------------
% 1st row
cy = cy + commonGeom.checkboxHeight + rowDelta;

% table options label
cx = col(1);
ctrlPos.tableLabel  = [cx cy tableLabelSize];

% table options edit field
cx = ctrlPos.descEdit(1);
ctrlPos.tableEdit  = [cx cy ctrlPos.descEdit(3:4)];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateTableCtrls creates Table controls page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateTableCtrls(pageNum, dlgfig, dlgdata)

% invoke standard function to create scaling controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
pageName = dlgdata.pageNames{pageNum};
% create the addoptGroupbox which will contain table values
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Table values'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% table controls
Children.tableLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Table:', ...
    'Position',           ctrlPos.tableLabel);

Children.tableEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.tableEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''tableEdit'')',pageName));

Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''useDDValueCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;

%-----------------------------------------------------------------------------------------
% FcnManageTableCtrls manages Table page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata,bModified] = FcnManageTableCtrls(pageNum, dlgfig, dlgdata, pageAction)

Children = dlgdata.pageData{pageNum}.children;

switch pageAction
    
    case 'tableEdit'
        tStr = deblank(get(Children.tableEdit, 'String'));
        if ~isempty(tStr)
            if strcmp(tStr, 'ddv')
                if isempty(dlgdata.data.table.variable)
                    beep;
                else
                    dlgdata.data.table.value = ['ddv(''', dlgdata.data.table.variable, ''')'];
                    dlgdata.data.table.useddvariablevalue = true;
                end
            else
                dlgdata.data.table.value = tStr;
            end
        else
            beep;
        end
        bModified = true;
        
    case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.table.value = ['ddv(''', dlgdata.data.table.variable, ''')'];
            dlgdata.data.table.useddvariablevalue = true;
            bRefreshTool = true;
        else
            dlgdata.data.table.useddvariablevalue = false;
        end
        bModified = true;
        
    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'table');
        [dlgdata, bModified2] = ...
            TLManageScalingCtrls('manage', pageNum, dlgfig, dlgdata, pageAction, 'table');
        
        bModified = bModified1 | bModified2;
end


%--------------------------------------------------------------------------
% FcnUpdateTableCtrls updates the controls of the Table tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateTableCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;

if dlgdata.data.tabisinput
    % disable all controls
    ctrlNames = fieldnames(Children);
    userData.ctrlStatus.enable = 'off';
    structfun(@(c) (set(c,'UserData',userData)), Children);
    TLSetCtrlsStatus(dlgfig, Children, ctrlNames);
    return
end

dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'table');

% get minima and maxima of table data
bReqMono = false;
bMatAllowed = dlgdata.data.ndims > 1;
[t, tmin, tmax, bCompliant] = tl_eval_table(dlgdata.data.table, bReqMono, bMatAllowed);
if bCompliant
    % constraints from table data only if 'table' is selected
    constraint = [tmin tmax];
else
    constraint = [];
end

dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'table', constraint);

tableEditCtrlStatus = struct('enable', 'on', 'string', '');
tableEditCtrlStatus.string = dlgdata.data.table.value;
tableEditCtrlStatus.iserror = ~bCompliant;
if dlgdata.data.table.useddvariablevalue
    tableEditCtrlStatus.enable = 'inactive';
end

% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.table.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.table.useddvariablevalue;

% read ranges' CtrlStatus
simulatedLabelCtrlStatus = tl_get_control_userdata(Children.simulatedLabel);
upperSimulatedValueCtrlStatus = tl_get_control_userdata(Children.upperSimulatedValue);
lowerSimulatedValueCtrlStatus = tl_get_control_userdata(Children.lowerSimulatedValue);

% update production code options for table variable
if ~isempty(t) && bCompliant
    minstr = sprintf('%0.5g', tmin);
    maxstr = sprintf('%0.5g', tmax);
else
    minstr = 'n.a.';
    maxstr = 'n.a.';
end
if dlgdata.data.ndims == 1
    simulatedLabelCtrlStatus.string = 'of vector';
else
    simulatedLabelCtrlStatus.string = 'of matrix';
end
upperSimulatedValueCtrlStatus.string = maxstr;
lowerSimulatedValueCtrlStatus.string = minstr;

% set control status
ctrlsList = {
    'tableEdit' ...
    'simulatedLabel' ...
    'upperSimulatedValue' ...
    'lowerSimulatedValue' ...
    'useDDValueCheckbox' ...
    };
for ctrlsNo = 1:numel(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of variable, scaling and table parameter groupbox controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLSetCtrlsStatus(dlgfig, Children, {'tableEdit', 'useDDValueCheckbox'});
